var app = getApp()
var baseUrl = app.globalData.baseUrl
Page({
  data: {
    articles: [],
    page: 1,
  },
  onShow() {
    //获取数据库第一页全部动态
    //this.getList()
    this.getArticle()
    //每次进入页面初始化显示的页面
    this.setData({
      page: 1
    })
  },
  getArticle(){
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: baseUrl+'article/getAllArticle/'+1,
      method: "POST",
      success: (res) => {
        let article = res.data
        let user = wx.getStorageSync('userInfo') //获取当前登录用户
        for (let t = 0; t < article.length; t++) {
          article[t].praiseStatus = false //初始化用户点赞状态
          //对于每一条动态，判断当前用户是否点赞了
          for (let j = 0; j < article[t].like.length; j++) {
            if (article[t].like[j] == user.id) {
              article[t].praiseStatus = true
              break
            }
          }
          if (t >= article.length - 1) {
            this.setData({
              articles: article
            })
            wx.hideLoading({
              success: (res) => {},
            })
          }
        }
      }
    })
  },
  //底部刷新函数
  onReachBottom: function () {
    //判断是否加载完
    if (this.data.articles.length % 20 != 0) {
      wx.showToast({
        title: '我是有底线哒~',
        icon: 'none'
      })
    } else {
      this.getNextList()
    }
  },
  onPullDownRefresh() {
    wx.showLoading({
      title: '刷新中',
    })
    //获取数据库第一页全部动态
    this.getList()
    //每次进入页面初始化显示的页面
    this.setData({
      page: 1
    })
    setTimeout(() => {
      wx.hideLoading({
        success: (res) => {},
      })
    }, 600)
  },
  //获取下一页数据并添加到总数据里面
  getNextList() {
    let page = this.data.page + 1
    wx.request({
      url: baseUrl+'article/getAllArticle/'+page,
      method: "POST",
      success: (res) => {
        let totalList = this.data.articles //先取出前面已经获取的数据
        let article = res.data
        let user = wx.getStorageSync('userInfo') //获取当前登录用户
        let num = 0
        for (let t = 0; t < article.length; t++) {
          article[t].praiseStatus = false //初始化用户点赞状态
          //对于每一条动态，判断当前用户是否点赞了
          if (article[t].like.length == 0) {
            totalList.push(article[t])
            num++
          } else {
            for (let j = 0; j < article[t].like.length; j++) {
              if (article[t].like[j] == user.id) {
                article[t].praiseStatus = true
                totalList.push(article[t])
                num++
                break
              }
              //用户没有点赞
              if (j == article[t].like.length - 1) {
                totalList.push(article[t])
                num++
              }
            }
          }
          if (num >= article.length) {
            console.log('数据', totalList)
            this.setData({
              articles: totalList, //覆盖数据
              page: page //页数加一
            })
          }
        }
      }
    })
  },
  //预览图片
  previewImg(e) {
    //获取当前动态的图片列表
    let imagesUrl = e.currentTarget.dataset.images
    //获取点击的图片索引
    let index = e.currentTarget.dataset.index
    wx.previewImage({
      urls: imagesUrl, //所有要预览的图片的地址集合 数组形式
      current: imagesUrl[index] //当前图片地址
    })
  },
  //点赞
  praise(e) {
    let user = wx.getStorageSync('userInfo')
    let articleId = e.currentTarget.dataset.articleid
    let index = e.currentTarget.dataset.ind
    if (!user) {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
      this.login()
    } else {
      if (this.data.articles[index].praiseStatus) {} else {
        let like = this.data.articles[index].like
        like.push(user.id)
        this.setData({
          ['articles[' + index + '].praiseStatus']: true,
          ['articles[' + index + '].like']: like
        })
        wx.request({
          url: baseUrl+'usersLike/addLike',
          method:'POST',
          data: {
            userId: user.id,
            article_id: articleId
          },
          success: res => {
            console.log(res)
          }
        })
      }
    }
  },
  //去发表动态
  publishArticle() {
    wx.navigateTo({
      url: '/pages/publishArticle/publishArticle',
    })
  },
  //查看动态评论
  toArticle(e) {
    let articleId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/article/article?articleId=' + articleId,
    })
    //增加点击量
    const _ = wx.cloud.database().command
    wx.request({
      url: baseUrl+'article/click/'+articleId,
      method: 'POST',
      success: res =>{
        console.log(res)
      }
    })
  },
  //访问其他人的动态
  toUserArticle(e) {
    let userOpenid = e.currentTarget.dataset.useropenid
    wx.navigateTo({
      url: '/pages/userArticle/userArticle?userOpenid=' + userOpenid,
    })
  },
  getOpenid() {
    wx.cloud.callFunction({
      name: 'get',
      complete: res => {
        let openid = res.result.openid;
        this.setData({
          openid: openid
        })
      }
    })
  },

  login() {
    this.getOpenid()
    wx.getUserProfile({
      desc: '获取用户信息',
      success: res => {
        var user = res.userInfo
        let user_openid = this.data.openid
        //设置局部用户信息
        this.setData({
          userInfo: user,
          hasUser: true
        })
        //检查数据库是否有该用户
        wx.request({
          url: baseUrl+'user/getUserInfo/'+user_openid,
          method:'GET',
          success: res => {
            console.log(res)
            //原先没有添加，这里添加
            if (!res.data) {
              //将数据添加到数据库
              wx.request({
                url: baseUrl+'user/addUser',
                method: 'POST',
                data: {
                  avatarUrl: user.avatarUrl,
                  nickName: user.nickName,
                  _openid: user_openid
                },
                success: res => {
                  console.log(增加的用户)
                  if(res.data){
                    wx.setStorageSync('userInfo',res.data)
                  }
                }
            }) 
          }else{
            wx.setStorageSync('userInfo', res.data)
          }
        }
    })
    }
  })
  },
})